package com.stox.client.api.data.provider;

import java.util.List;

import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.Cache;
import com.stox.shared.core.model.filter.BarCriteria;

public class CachingBarClient implements BarClient {

	private final BarClient delegate;
	private final Cache<BarCriteria, List<Bar>> cache;
	
	public CachingBarClient(BarClient delegate, int maxEntries) {
		this.delegate = delegate;
		this.cache = new Cache<>(maxEntries);
	}
	
	@Override
	public synchronized List<Bar> find(BarCriteria barCriteria) {
		List<Bar> result = cache.get(barCriteria);
		if(null == result){
			result = delegate.find(barCriteria);
			cache.put(barCriteria, result);
		}else{
			if(barCriteria.getBarSpan().previous().after(barCriteria.getTo())){
				result = delegate.find(barCriteria);
				cache.put(barCriteria, result);
			}
		}
		return result;
	}

}
